package com.guijianpan.framework.context;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程会话，缓存数据<br>
 * 使用ThreadLocal模拟HttpSession，共享会话缓存数据，各个java方法中不需要传递HttpSession参数即可获取用户会话缓存数据<br>
 * @author yzChen  2015-5-14 09:22:46
 */
public class ThreadSession {

	private static final ThreadLocal<Map<Object, Object>> local = new ThreadLocal<Map<Object, Object>>();

	/**
	 * 回收线程对象<br>
	 * 注：只要不往不用的threadlocal中放入大量数据，可忽略调用此方法，在线程结束时，会自动回收
	 */
	public static void clear() {
		local.remove();
	}
	
	public static void put(Object key, Object value) {
		Map<Object, Object> map  = local.get();
		if(null == map) {
			map = new HashMap<Object, Object>();
			local.set(map);
		}
		map.put(key, value);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T get(Object key) {
		Map<Object, Object> map  = local.get();
		if(null == map) {
			return null;
		}
		return (T) map.get(key);
	}

}
